<template>
	<uni-popup ref="popup" type="bottom" @change="change">
		<!-- <g-navbar title="选择代理商"/> -->
		<view class="agent-list-popup">
			<searchBar placeholder="请输入代理商昵称" v-model="searchKey" :isShowBackBtn="true" :isShowSearchBtn="false"
				@onClickBack="onClickBack" />
			<view class="list-wrapper" v-if="isShowList">
				<uni-indexed-list :options="agentListFormatted" @click="selectAgent" />
			</view>
		</view>
	</uni-popup>
</template>

<script lang="ts" setup>
	import { onMounted, Ref, ref, defineProps, computed, defineEmits } from 'vue';
	import { IPopupExpose, IPopupChange, IIndexListClickEvent } from '../../types';
	import searchBar from '../search-bar/searchBar';
	import { IAgent, ITempItem, ITempArrItem } from './types';
	import { makePy, isLetter, arrangementByalphabet } from '@/utils';

	const popup : Ref<null | IPopupExpose> = ref(null);

	const emit = defineEmits(['selectAgent']);


	const isShowList : Ref<boolean> = ref(false);

	const searchKey : Ref<string> = ref('');

	interface IProps {
		agentList : IAgent[]
	}

	const props = withDefaults(defineProps<IProps>(), {
		agentList: () => []
	})




	const agentListFormatted = computed(() => {
		let tempObj : { [propname : string] : ITempItem[] } = {};
		for (let item of props.agentList) {
			const first_letter = makePy(item.agent_name)[0];
			const temp : ITempItem = {
				value: item.agent_name,
				id: item.id,
			}

			if (temp.value.includes(searchKey.value)) {
				if (isLetter(first_letter)) {
					tempObj[first_letter] ? tempObj[first_letter].push(temp) : tempObj[first_letter] = [temp];
				} else {
					tempObj['#'] ? tempObj['#'].push(temp) : tempObj['#'] = [temp];
				}
			}
		}

		tempObj = arrangementByalphabet(tempObj);
		const tempArr : ITempArrItem[] = [];
		for (let key in tempObj) {
			const tempArrItem : ITempArrItem = {
				letter: key,
				data: tempObj[key],
			}
			tempArr.push(tempArrItem);
		}
		return tempArr
	})







	let timer : number;


	const change = (e : IPopupChange) => {
		clearTimeout(timer);
		timer = setTimeout(() => {
			isShowList.value = e.show;
		}, 300)

	}

	const selectAgent = (e : IIndexListClickEvent) => {
		emit('selectAgent', { value: e.item.name, id: e.item.id });
		popup.value?.close!();
	}


	const open = () => {
		popup.value?.open();
	}

	const onClickBack = () => {
		searchKey.value = '';
		popup.value?.close!();
	}


	defineExpose<IPopupExpose>({
		open
	})
</script>

<style scoped lang="scss">
	@import "./agentListPopup.scss";
</style>